from PyQt5.QtWidgets import QStyledItemDelegate
from PyQt5.QtWidgets import QDateTimeEdit
from PyQt5.QtCore import Qt, QDateTime

class QMyDateTimeEdit(QStyledItemDelegate):
    def __init__(self, parent=None):
        super().__init__()

    #用于创建需要的编辑器组件
    def createEditor(self, parent, option, index):
        editor = QDateTimeEdit(parent)
        editor.setDisplayFormat('yyyy-MM-dd hh:mm:ss.z')
        return editor

    #从数据模型获取数据，设置编辑器的值
    def setEditorData(self, editor, index):
        model = index.model()
        # print(type(index), type(model))
        datetime = model.data(index, Qt.EditRole)
        # dttm = QDateTime.fromString(text, 'yyyy-MM-dd hh:mm:ss:z')
        editor.setDateTime(datetime)

    #将代理编辑器上的值更新到数据模型
    def setModelData(self, editor, model, index):
        n_datetime = editor.dateTime()
        model.setData(index, n_datetime,Qt.EditRole)

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    #这个用来重写传递过来的数据
    def displayText(self, text, locale):
        '''
        :param text: model传递来的参数，具体什么类型需要看具体的需求
        :param locale:
        :return:
        '''
        data = text.toString('yyyy-MM-dd hh:mm:ss.z')
        return data

